<template>
  <div class="screen">
    <!-- 头部 -->
    <topContainer @getId='getId' :name='topName' @fullscreen='fullscreen' @setBoard="setBoard"></topContainer>

    <div class="boardContainer">
      <div class="cardList scrollNone">
        <div class="card" :style="{width:setWidth}" v-for="item in lampDashboardList" :key="item.processId">
          <div class="card-item" :style="{fontSize:setFont}">
            <div class="cardTitle" :style="{color:handleTitleColor(item.dashboardLampRequestVos)}">
              <span class="ellipsis">{{item.deviceSn}}</span>
              <span class="ellipsis">{{item.deviceName}}</span>
            </div>
            <div class="card-body">
              <div class="piebox" v-for="(i,index) in item.dashboardLampRequestVos" :key="index"
                :class="handelClass(item.dashboardLampRequestVos)" :style="{backgroundColor:handleSingleBg(item.dashboardLampRequestVos)}">
                <div class="boxInner" v-show="item.dashboardLampRequestVos.length < 2"
                  :style="{background:i.color}">
                  <span class="state">{{i.dealStatus}}</span>
                  <span class="event ellipsis" style="width:100%;display:inline-block">{{i.typeName}}</span>
                  <span class="time ellipsis" style="width:100%;display:inline-block">{{i.durationName}}</span>
                </div>
                <div class="boxInner" v-show="item.dashboardLampRequestVos.length >= 2"
                  :style="{background:i.color}">
                  <div>
                    <span class="event">{{i.typeName}}</span>
                    <span class="state">{{handleResponseInfo(i.dealStatus,i.responseUserName)}}</span>
                  </div>
                </div>
              </div>
              <div v-if="item.dashboardLampRequestVos === null || !item.dashboardLampRequestVos.length"
                style="width:100%;height:100%;align-items: center;display: flex;justify-content: center;font-size:1.6em;font-weight:650">
                <span>无请求</span>
              </div>
            </div>
            <div class="card-bottom">
              <span class="ellipsis" :style="{color:handleByInfo(item.dashboardLampRequestVos,'color')}">
                {{handleByInfo(item.dashboardLampRequestVos,'responseUserName')}}
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <setBoard ref="setBoard" @confirm="confirm" :groupId="groupId" :checkGroup="checkGroup"></setBoard>
  </div>
</template>

<script>
  const activeIndex = 0
  import audioUrl from '@/assets/audio/t-rex-roar.mp3'
  import {
    lampDashboard
  } from '@/api/lampController'
  import {
    getSearchCache
  } from '@/api/produceController'
  import {
    lampTypeDropDown
  } from '@/api/lampController'
  import setBoard from './setBoard.vue'
  export default {
    data() {
      return {
        topName: '联络灯看板',
        lampDashboardList: [],
        groupId: '',
        windowMsg: null,
        speechList: [],
        checkGroup:[],
        interfaceFlag: true,
        cacheInfo: {}
      }
    },
    components:{
      setBoard
    },
    computed: {
      //单个请求的背景色
      handleSingleBg() {
        const index = 0
        return dashboardLampRequestVos => {
          if (dashboardLampRequestVos.length == 1) {
            return dashboardLampRequestVos[index].color
          }
        }
      },
      //底部人员信息
      handleByInfo() {
        const index = 0
        return (dashboardLampRequestVos, key) => {
          if (dashboardLampRequestVos.length == 1) {
            return dashboardLampRequestVos[index][key]
          }
        }
      },
      //cardTitle color
      handleTitleColor() {
        return dashboardLampRequestVos => {
          const index = 0
          return dashboardLampRequestVos.length ? dashboardLampRequestVos[index].color : '#999'
        }
      },
      handleResponseInfo() {
        return (dealStatus, responseUserName) => {
          return dealStatus == '等待响应' ? dealStatus : responseUserName + '...' + '处理中'
        }
      },
      handelClass() {
        return detail => {
            return detail !== null && detail.length >= 2 ? 'multiple' : 'single'
        }
      },
      setWidth() {
        return (100 / this.cacheInfo.number) + '%'
      },
      setFont() {
        return (90 / this.cacheInfo.number) + 'px'
      },
    },
    mounted() {
      this.getSearchCacheFn({
        cacheName: 'board:set',
        type: 0
      })
      this.windowMsg = new window.SpeechSynthesisUtterance();
    },
    methods: {
      //分组id
      getId(groupId) {
        this.groupId = groupId
        this.lampTypeDropDownFn({groupId}).then(()=>{
          if(!this.cacheInfo[this.groupId + '@@']){
            this.cacheInfo[this.groupId + '@@'] = this.checkGroup.map(i => i.value)
          }
          this.handleInterface()
        })
      },
      lampTypeDropDownFn:async function (data) {
          const res = await lampTypeDropDown(data)
          this.checkGroup = res.data
      },
      //看板列表
      getLampDashboard: async function (data) {
        const res = await lampDashboard(data)
        if (res.code == 200) {
          const {
            interval
          } = this.cacheInfo
          this.lampDashboardList = res.data.listData.records
          if (res.data.voiceCallsInfos !== null && Object.keys(res.data.voiceCallsInfos).length > 0) {
            res.data.voiceCallsInfos.forEach(i => {
              this.speechList.push({
                text: i.text,
                time: 0
              })
            })
            if (this.speechList.length && this.interfaceFlag) {
              this.play(this.speechList[activeIndex])
            }
          }
          clearInterval(window.boardTimer)
          window.boardTimer = setInterval(() => {
            this.handleInterface()
          }, interval * 1000)
        }
      },
      //获取缓存信息
      getSearchCacheFn: async function (data) {
          const res = await getSearchCache(data)
          this.cacheInfo = res.data !== null ? JSON.parse(res.data) : {
            number: 9,
            interval: 10,
            [this.groupId + '@@']:this.checkGroup.map(i => i.value),
            haveRequest: false
          }
      },
      fullscreen(isFull) {
        let elem = document.querySelector(".screen");
        isFull ? elem.requestFullscreen() : document.exitFullscreen()
      },
      setBoard() {
        let jsonData = JSON.parse(JSON.stringify(this.cacheInfo))
        this.$refs.setBoard.open(jsonData)
      },
      confirm(form) {
        this.cacheInfo = form
        this.handleInterface()
      },
      handleInterface() {
        let type = this.cacheInfo[this.groupId + '@@']
        this.getLampDashboard({
            groupId: this.groupId,
            haveRequest: this.cacheInfo.haveRequest,
            maxLampRequestNum:4,
            type:type ? type.toString() : ''
        })
      },
      removeTag(tagList) {
        tagList.forEach(i => i.remove())
      },
      play(data) {
        this.interfaceFlag = false
        const audioNode = document.createElement('audio')
        const screenNode = document.querySelector('.screen')
        audioNode.src = audioUrl
        audioNode.autoplay = 'autoplay'
        screenNode.appendChild(audioNode)
        if (!this.windowMsg) {
          this.windowMsg = new window.SpeechSynthesisUtterance()
        }
        this.windowMsg.text = data.text;
        this.windowMsg.rate = 0.8;
        this.windowMsg.onerror = (e) => {
          if (e.error === 'interrupted') return
          this.utils.showMsg('系统错误,请重新发起联络灯请求', 'error')
        }
        this.windowMsg.onend = () => {
          this.speechList[activeIndex].time++
          if (this.speechList[activeIndex].time > 2) {
            this.speechList.splice(activeIndex, 1) //播放次数达到三次以后从数组中删除
          }
          if (this.speechList.length === 0) {
            this.interfaceFlag = true
            //移除所有标签
            this.removeTag(document.querySelectorAll('audio'))
            speechSynthesis.cancel()
            return
          }
          this.play(this.speechList[activeIndex])
        }
        audioNode.addEventListener('ended', () => {
          speechSynthesis.speak(this.windowMsg);
        })
      },
    },
    beforeRouteLeave(to, from, next) {
      clearInterval(window.boardTimer)
      next()
    }
  }
</script>

<style lang="less" scoped>
  .screen {
    padding: 20px;
    background-color: #000;
    overflow-y: auto;
    height: 100%;

    .top {
      height: 56px;
      margin-bottom: 20px;
    }

    .boardContainer {
      border: 1px solid rgba(58, 200, 243, .8);
      height: calc(100% - 76px);
      padding: 10px 0 0 15px;

      .cardList {
        display: flex;
        flex-wrap: wrap;
        height: calc(100% - 19px);
        overflow-y: auto;
        align-content: flex-start;

        .card {
          padding-right: 15px;

          .card-item {
            margin-top: 15px;
            background-color: #e3fdf7;
            border-radius: 8px;

            .cardTitle {
              display: flex;
              flex-direction: column;
              font-size: 1.4em;
              height: 3em;
              color: #999;
              padding: 0 0.5em 0 0.5em;
              text-align: left;

            }

            .card-body {
              height: 13em;
              color: #fff;
              background-color: #999999;
              display: flex;
              flex-direction: column;

              .piebox {
                width: 100%;

                .state,
                .event,
                .time {
                  font-size: 1.6em;
                }
              }
            }

            .piebox.single {
              height: 100%;

              .boxInner {
                display: flex;
                height: 100%;
                flex-direction: column;
                align-items: center;
                justify-content: center;
                text-align: center;

                .state {
                  font-size: 1.2em;
                }
                .event,.time{
                  font-weight: 650;
                }
              }
            }

            .piebox.multiple {
              flex: 1;

              .boxInner {
                width: 100%;
                height: 100%;
                padding-left: 0.5em;
                display: flex;
                align-items: center;
                .event {
                  font-weight: 650;
                  padding-right: 0.5em;
                }
                .state{
                  font-weight: 650;
                  font-size: 1.2em;
                }
              }
            }

            .card-bottom {
              height: 2.5em;
              line-height: 2.5em;
              font-size: 1.4em;
              padding: 0 0.5em 0 0.5em;
              text-align: center;
            }
          }
        }

        .ellipsis {
          width: 100%;
          display: inline-block;
          text-overflow: ellipsis;
          overflow: hidden;
          white-space: nowrap;
        }
      }
    }
  }
</style>